package com.ux.base
{
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLVariables;
	
	/**
	 * @author winnie
	 */	
	public class BUrlLoader extends URLLoader
	{
		private var _fn : Function;
		private var _req : URLRequest;
		private var _url : String;
		private var _params : URLVariables;
		private var _loadingPercentage : int;
		private var _loadData : String;
	
		/**
		 * @param url				: 로딩 url
		 * @param completeHandler	: 완료 핸들링 메서드
		 * @param request			: null;
		 */		
		public function BUrlLoader( url:String, completeHandler:Function=null, params:Object=null, method:String="post" )
		{
			super();
			
			trace("url",url);
			this._url = url;
			_req = new URLRequest();
			_req.url = _url;
			
			if( completeHandler != null ) this._fn = completeHandler;
			if( params != null )
			{
				_params = new URLVariables();
				
				for( var key:String in params )
				{
					_params[ key ] = params[ key ];
				}
				
				_req.data = _params;
				_req.method = method;
				
			}
			
			
			
			this.addEventListener(Event.COMPLETE, onUrlLoadComplete );
			this.addEventListener(IOErrorEvent.IO_ERROR, onIOErrorEvent );
			this.addEventListener(ProgressEvent.PROGRESS, onProgressEvent );
			this.load( _req );
			
		}
		
		
		private function onUrlLoadComplete( e:Event ):void
		{
			this._loadData = String( this.data );
			if( _fn != null ) this._fn( this );
		}
		
		
		private function onIOErrorEvent( e:IOErrorEvent ):void
		{
			throw new Error( "URL Loader 로드중 에러발생 type : IOErrorEvent" );
		}
		
		
		private function onProgressEvent( e:ProgressEvent ):void
		{
			this._loadingPercentage = Math.floor( e.bytesLoaded / e.bytesTotal );
		}
		
		
		/**
		 * return load Data
		 */		
		public function get loadData():String
		{
			if( _loadData == null ) 
			{
				throw new Error( "URL Loader 에서 로드되지 않은 데이터에 접근 했습니다." );
				return;
			}
			
			return this._loadData;
		}
		
		/**
		 *  return loading percentage. 
		 */		
		public function get loadingPercentage():int
		{
			return _loadingPercentage;
		}
		
	}
}